package com.cloud.shopping.order.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cloud.shopping.constants.RocketConstants;
import com.cloud.shopping.order.model.Order;
import com.cloud.shopping.order.model.OrderRefund;
import com.cloud.shopping.order.service.OrderService;
import com.cloud.shopping.pay.WeChatPayParam;
import com.cloud.shopping.tool.RespCode;
import com.cloud.shopping.tool.RespResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author John.zhang
 * @version Id: OrderController, v 1.0 2021/1/3 21:06 ZhiYong Exp $
 */

@RestController
@RequestMapping(value = "/order")
@CrossOrigin
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private WeChatPayParam weChatPayParam;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 申请取消订单
     *
     * @param id      id
     * @param request request
     * @return RespResult
     * @throws Exception
     */
    @PutMapping(value = "/refund/{id}")
    public RespResult refund(@PathVariable(value = "id") String id, HttpServletRequest request) throws Exception {
        //用户名
        String username = "gp";
        //查询订单，是否符合退款要求
        Order order = orderService.getById(id);
        if (order.getPayStatus() == 1 && order.getOrderStatus() == 1) {
            //添加退款记录,更新订单状态
            OrderRefund orderRefund = new OrderRefund(
                    IdWorker.getIdStr(),
                    id,
                    1,
                    null,
                    username,
                    //申请退款
                    0,
                    new Date(),
                    order.getMoneys()
            );
            orderService.refund(orderRefund);

            //向MQ发消息（申请退款）  out_trade_no（订单号）  out_refund_no（退款订单号）  total_fee（订单金额）  refund_fee（退款金额）
            Message message = MessageBuilder.withPayload(weChatPayParam.weChatRefundParam(orderRefund)).build();
            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(RocketConstants.PRODUCER_GROUP, RocketConstants.REFUND_TOPIC, message, orderRefund);

            if (transactionSendResult.getSendStatus() == SendStatus.SEND_OK) {
                return RespResult.ok();
            }
        }
        //不符合直接返回错误
        return RespResult.error("当前订单不符合取消操作要求！");
    }


    /**
     * 添加订单
     *
     * @param order order
     * @return RespResult
     */
    @PostMapping
    public RespResult add(@RequestBody Order order, HttpServletRequest request) throws Exception {
        //用户名字
        order.setUsername("John");
        //下单
        Boolean bo = orderService.add(order);
        String content = weChatPayParam.weChatParam(order, request);
        return bo ? RespResult.ok(content) : RespResult.error(RespCode.ERROR);
    }
}
